<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Admin;
use Illuminate\Support\Facades\Hash;

class AdminController extends BaseController
{
    //用户列表显示
    public function index()
    {

        $data = Admin::orderBy('id', 'desc')->paginate(5);


        return view('admin.user.index', compact('data'));
    }


    //新用户添加展示
    public function create()
    {
        return view('admin.user.create');
    }

    // 添加用户处理
    public function store(Request $request)
    {
        $data = $this->validate($request, [
            'username' => 'required|unique:admins,username',
            'password' => 'required|confirmed',
            'truename' => 'required',
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
            'email' => 'required|email',
            'sex' => 'required'

        ], [
            'username.required' => '用户名不能为空',
            'password.required' => '密码不能为空',
            'truename.required' => '真实姓名不能为空',
            'truename.required' => '真实姓名不能为空',
            'phone.required' => '手机不能为空',

        ]);
        $data['password'] = Hash::make($data['password']);
        $d = Admin::create($data);
        if ($d) {
            // return redirect(route('admin.admin.index'))->with('sucess','添加用户成功');
            echo "<script>parent.location.reload();</script>";
        }
    }

    //用户删除操作

    public function destory($id)
    {


        Admin::destroy($id);
        return ['sucess' => '200', 'msg' => '删除成功'];
    }

    public function destoryall(Request $request)
    {


        $id = $request->get('id');
        $id = explode(',', $id);

        Admin::destroy($id);
        return ['sucess' => '200', 'msg' => '删除成功'];
    }

    public function edit(Request $request, $id)
    {

        if ($request->isMethod('post')) {

    
           $data=$this->validate($request,[   
            'truename' => 'required',
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
            'email' => 'required|email',
            'sex' => 'required'

        ], [
            
            'truename.required' => '真实姓名不能为空',
            'truename.required' => '真实姓名不能为空',
            'phone.required' => '手机不能为空',

        ]);
          
        Admin::where('id',$id)->update($data);
        echo "<script>alert('修改成功');parent.location.reload();</script>";

        } else {
            $data = Admin::where('id', $id)->get()->toarray()[0];

            return view('admin.user.edit', compact('data'));
        }
    }
}
